<template>
  <j-modal :title="title" :width="width" :visible="visible" switchFullscreen @cancel="handleCancel" :footer="null">
    <div class="contentBox">
      <div class="formBox">
        <a-form-model ref="ruleForm" :rules="rules" :model="form" :label-col="labelCol" :wrapper-col="wrapperCol">
          <a-form-model-item label="被谈话人" prop="realName">
            <a-input v-model="form.realName" :disabled="isDisabled" placeholder="请输入" />
          </a-form-model-item>
          <a-form-model-item label="身份证号" prop="identityCard">
            <a-input v-model="form.identityCard" :disabled="isDisabled" placeholder="请输入" />
          </a-form-model-item>
          <a-form-model-item label="访谈类型" prop="type">
            <a-select v-model="form.type" :disabled="isDisabled" placeholder="请选择">
              <a-select-option value="1">定期访谈</a-select-option>
              <a-select-option value="2">日常访谈</a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="次数" prop="interviewNum">
            <a-input v-model="form.interviewNum" :disabled="isDisabled" placeholder="请输入" />
          </a-form-model-item>
          <a-form-model-item label="访谈分类" prop="interviewClassificationId">
            <a-tree-select style="width:100%" allowClear :dropdownStyle="{ maxHeight: '200px', overflow: 'auto' }"
              :treeData="treeData" v-model="form.interviewClassificationId" @change="onChange" placeholder="请选择">
            </a-tree-select>
          </a-form-model-item>
          <a-form-model-item class="sItem" label="是否启用模板">
            <a-switch v-model="form.delivery" @change="onSwitchChange" />
            <a-tooltip placement="rightBottom" style="position: absolute;left: 70px;top: 5px;"
              :overlayStyle="{ minWidth: `300px`, maxWidth: `400px` }">
              <template slot="title">
                <div>启用模板调取的是对应访谈分类下的访谈模板内容</div>
              </template>
              <a-icon type="question-circle" />
            </a-tooltip>
          </a-form-model-item>
          <a-form-model-item label="访谈主题" prop="interviewTheme">
            <a-input v-model="form.interviewTheme" placeholder="请输入" />
          </a-form-model-item>
          <InterviewItem ref="interviewItemId" :isHaveAnswer="false" />
          <a-form-model-item label="访谈资料">
            <j-upload v-model="form.applyFile" :number="1"></j-upload>
            <p>支持扩展名：.rar .zip .doc .docx .pdf .jpg...</p>
          </a-form-model-item>
          <a-form-model-item label="开始时间" prop="interviewAppointmentStartTime">
            <a-date-picker v-model="form.interviewAppointmentStartTime" style="width:100%;" show-time
              format="YYYY-MM-DD HH:mm" valueFormat="YYYY-MM-DD HH:mm" allowClear placeholder="请选择" />
          </a-form-model-item>
          <a-form-model-item label="结束时间" prop="interviewAppointmentEndTime">
            <a-date-picker v-model="form.interviewAppointmentEndTime" style="width:100%;" show-time
              format="YYYY-MM-DD HH:mm" valueFormat="YYYY-MM-DD HH:mm" allowClear placeholder="请选择" />
          </a-form-model-item>
          <a-form-model-item label="谈话地点" prop="interviewPlaceIdArr">
            <!-- {{form.interviewPlaceIdArr}} -->
            <z-linkage-area placeholder="请选择行政区划" v-model="form.interviewPlaceIdArr" @rows="onRows"
              @change="setAdminDivisions" />
          </a-form-model-item>
          <a-form-model-item label="详细地址" prop="detailPlace">
            <a-input v-model="form.detailPlace" placeholder="请输入" />
          </a-form-model-item>
        </a-form-model>
        <div class="btnBox">
          <a-button>取消</a-button>
          <a-button type="primary" :loading=loading style="margin-left: 50px;" @click="onSubmit">确定</a-button>
        </div>

      </div>
      <Schedule class="scheduleBox" ref="scheduleId" />
    </div>
  </j-modal>
</template>
<script>
import Schedule from '@/views/sjsk/modules/Schedule'
import InterviewItem from '@/views/sjsk/helpManage/modules/InterviewItem'
import * as uroscopyApi from '@/api/sjsk/check/uroscopy.js'
import * as interviewApi from '@/api/sjsk/help/interview.js'
import Vue from 'vue'
import { USER_INFO } from "@/store/mutation-types"
export default {
  name: 'BookingModal',
  props: ['title'],
  components: {
    Schedule, InterviewItem
  },
  data() {
    return {
      width: 1200,
      visible: false,
      visible1: false,
      labelCol: { span: 24 },
      wrapperCol: { span: 24 },
      form: {},
      rules: {
        realName: [{ required: true, message: '请选择' }],
        sjskPersonId: [{ required: true, message: '请选择' }],
        identityCard: [{ required: true, message: '请输入' }],
        type: [{ required: true, message: '请选择' }],
        interviewNum: [{ required: true, message: '请输入' }],
        interviewClassificationId: [{ required: true, message: '请选择' }],
        interviewTheme: [{ required: true, message: '请选择' }],
        interviewAppointmentStartTime: [{ required: true, message: '请选择' }],
        interviewAppointmentEndTime: [{ required: true, message: '请选择' }],
        interviewPlaceIdArr: [{ required: true, message: '请选择' }],
        detailPlace: [{ required: true, message: '请输入' }],
      },
      isDisabled: true,
      treeData: [],
      loading: false,
      isSwitchOpen: false
    }
  },
  methods: {
    show(type, record) {
      this.visible = true
      this.isSwitchOpen = false
      this.form = { isTemplate: 2 } //默认不开启模板
      this.getTypeData() //获取访谈分类列表数据
      this.getBookDetail(record.id, type) //获取预约详情
      this.getPlan() //获取日程预约数据
    },
    getBookDetail(id, type) {
      interviewApi.interviewRecordDetail(id).then((res) => {
        if (res.success) {
          if (type == 2) { //预约，只读个人基本信息回填
            this.$set(this.form, "type", "1")//固定未定期访谈
            this.$set(this.form, "id", id)
            this.$set(this.form, "sjskPersonId", res.result.sjskPersonId)
            this.$set(this.form, "realName", res.result.realName)
            this.$set(this.form, "identityCard", res.result.identityCard)
            this.$set(this.form, "interviewNum", "第" + res.result.interviewNum + "次")
            this.$set(this.form, "interviewEndTime", res.result.interviewEndTime) //注意要传访谈结束时间interviewEndTime
          }
          if (type == 3) { //改约，读取预约信息回填
            this.form = res.result ? res.result : {}
            this.form.type = "1"  //固定未定期访谈
            this.form.id = id
            this.$set(this.form, "interviewNum", "第" + res.result.interviewNum + "次")
            if (this.form.isTemplate == 1) {
              this.$set(this.form, "delivery", true)
            } else {
              this.$set(this.form, "delivery", false)
            }
            //设置访谈内容
            let obj = {
              base: res.result.base,
              analyze: res.result.analyze,
              expand: res.result.expand
            }
            this.$refs.interviewItemId.setData(obj)
            //设置访谈地址
            this.form.interviewPlaceIdArr = res.result.interviewPlaceId.split(',')
          }
        } else {
          this.$message.success(res.message)
        }
      })
        .catch((e) => {
          this.$message.warning(res.message)
        })
    },
    onSwitchChange(e) {
      if (e) {
        this.isSwitchOpen = true
        console.log(this.form.interviewClassificationId)
        if (this.form.interviewClassificationId == undefined) {
          this.$message.warning("请选择访谈分类")
          return
        }
        this.getTemplateDetail() //读取模板内容
        this.form.isTemplate = 1
      } else {
        this.isSwitchOpen = false
        this.form.isTemplate = 2
      }
    },
    onChange(value, label) {
      // console.log(value, label)
      this.form.interviewClassification = label[0]
      // console.log(this.form.interviewClassification)
      if (this.isSwitchOpen) {
        this.getTemplateDetail() //读取模板内容
      }
    },
    // 获取行政区划的值
    setAdminDivisions(value) {
      // console.log("1111")
      // console.log(value)
      // let data = value? value.filter(item=>{ return item }): []
      // let lastData = data.length>0?data[data.length-1]:''
      // this.$set(this.model, 'adminDivision', lastData)
      // this.$set(this.model, 'adminDivisionLevel', data.length)
      // this.$set(this.model, 'adminDivisionStr', data.toString())
    },
    onRows(row) {
      // console.log("value")
      // console.log(row)
      let str = ""
      row.forEach(item => {
        str += item.title + "," //保存行政区划名称
      })
      this.form.interviewPlace = str.slice(0, str.length - 1) //删除最后一个逗号
      // console.log(this.form.interviewPlace)
    },
    getTypeData() {
      interviewApi.classificationTree().then((res) => {
        if (res.success) {
          this.treeData = res.result ? res.result : {}
          this.generateList(this.treeData)
        } else {
          this.$message.success(res.message)
        }
      })
        .catch((e) => {
          this.$message.warning(res.message)
        })
    },
    generateList(data) {
      for (let i = 0; i < data.length; i++) {
        const node = data[i];
        // 不是叶子节点都不能选
        if (node.children && node.children !== null && node.children.length > 0) {
          // if (node.sortNum == 1) {
          //   node.disabled = true;
          // }
        } else {
          if (node.sortNum == 2) { //没有添加过模块的置灰，不可选择
            node.disabled = true;
          }
        }
        if (node.children) {
          this.generateList(node.children);
        }
      }
    },
    getTemplateDetail() {
      interviewApi.InterviewClassificationDetail(this.form.interviewClassificationId).then(res => {
        if (res.success) {
          if (res.result != null) {
            this.$set(this.form, 'interviewTheme', res.result.interviewTheme)
            this.$set(this.form, 'applyFile', res.result.applyFile)
            let obj = {
              base: res.result.base,
              analyze: res.result.analyze,
              expand: res.result.expand
            }
            this.$refs.interviewItemId.setData(obj)
          }
        }
      })
    },
    getPlan() {
      let userInfo = Vue.ls.get(USER_INFO)
      uroscopyApi.planList(userInfo.id).then((res) => {
        if (res.success) {
          let scheduleData = []
          if (res.result.length > 0) {
            res.result.forEach(item => {
              if (item.overdue == 1) { //1为逾期，变红
                scheduleData.push({
                  id: item.id,
                  title: item.title,
                  start: item.startTime,
                  end: item.endTime,
                  overdue: item.overdue,
                  textColor: 'red',
                  className: ["bgColor", "monthRedColor"]
                })
              } else {
                scheduleData.push({
                  id: item.id,
                  title: item.title,
                  start: item.startTime,
                  end: item.endTime,
                  overdue: item.overdue,
                  textColor: '#000',
                  className: ["bgColor", "monthBlackColor"]
                })
              }
            })
            this.$refs.scheduleId.setScheduleData(scheduleData)
          }
          // this.scheduleData = [
          //   {
          //     id: 111,
          //     title: '张三的常规尿液检测11',
          //     start: '2022-12-3 02:30:00',
          //     end: '2022-12-10 06:00:00',
          //     overdue: "1"
          //   },
          //   {
          //     id: 222,
          //     title: '张三的常规尿液检测22',
          //     start: '2022-12-10 08:30:00',
          //     end: '2022-12-10 10:00:00',
          //     overdue: "1"
          //   },
          //   {
          //     id: 333,
          //     title: '吃药了吗',
          //     start: '2022-12-14 02:30:00',
          //     end: '2022-12-14 06:00:00',
          //     overdue: "2"
          //   },
          //   {
          //     id: 444,
          //     title: '林国强的常规尿液检测',
          //     start: '2022-12-16 02:30:00',
          //     end: '2022-12-16 06:00:00',
          //     overdue: "2"
          //   }]
          // this.$refs.scheduleId.setScheduleData(this.scheduleData)
        }
      })
        .catch((e) => {
          this.$message.warn('请求失败！')
        })
    },
    isSameDay(startTime, endTime) {
      const startTimeMs = new Date(startTime).setHours(0, 0, 0, 0);
      const endTimeMs = new Date(endTime).setHours(0, 0, 0, 0);
      return startTimeMs === endTimeMs ? true : false
    },
    onSubmit() {
      this.form.interviewPlaceId = this.form.interviewPlaceIdArr.join() //访谈地址id转字符串
      let itemData = this.$refs.interviewItemId.getData() //获取访谈访谈大纲
      if (itemData != undefined) {
        this.form = Object.assign(this.form, itemData)
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            let flag = this.isSameDay(this.form.interviewAppointmentStartTime, this.form.interviewAppointmentEndTime)
            if (!flag) {
              this.$message.warning("预约开始时间和结束时间必须是同一天内！")
              return
            }
            this.form.interviewNum = this.form.interviewNum.substring(1, this.form.interviewNum.length - 1) //截取数字字符,即次数
            //验证是否预约时间冲突
            let userId = Vue.ls.get(USER_INFO).id
            let params = {
              userId: userId,
              startTime: this.form.interviewAppointmentStartTime,
              endTime: this.form.interviewAppointmentEndTime
            }
            interviewApi.checkPlan(params).then(res => {
              if (res.success) {
                if (res.result) { //true表示预约时间冲突
                  let that = this
                  this.$confirm({
                    title: `当前时间段已有1个行程，确定要继续添加吗？?`,
                    okText: "确认",
                    okType: "danger",
                    cancelText: "取消",
                    onOk() {
                      that.addInterview()
                    }
                  });
                } else { //无预约时间冲突
                  this.addInterview()
                }
              }
            })
          }
        })
      }
    },
    addInterview() {
      this.loading = true
      interviewApi.addInterviewRecordAppointment(this.form).then(res => {
        if (res.success) {
          this.$message.success(res.message)
          this.$emit('ok');
          this.visible = false
          this.loading = false
        } else {
          this.loading = false
          this.$message.warn(res.message)
        }
      })
        .catch(e => {
          this.loading = false
          this.$message.warn('请求失败！')
        })
    },
    handleCancel() {
      this.$emit('close')
      this.visible = false
    },
  },
}
</script>
<style lang="less" scoped>
.contentBox {
  display: flex;
  height: 800px;
  position: relative;

  .formBox {
    flex: 1;
    height: 90%;
    overflow-y: auto;
    padding-right: 20px;

    .btnBox {
      position: absolute;
      bottom: 0;
      padding: 15px 0 0 70px;
      left: -20px;
      width: 320px;
      height: 60px;
      background-color: #fff;
    }
  }

  .scheduleBox {
    flex: 3;
    margin-left: 20px;
    padding-right: 20px;
  }
}

.mbkBtn {
  position: absolute;
  top: 5px;
  left: 130px;
}

/deep/.ant-col-24 {
  text-align: left;
}

/deep/.ant-row {
  margin-bottom: 10px;
}


/deep/.ant-col-24 {
  padding-bottom: 5px;
}

.sItem {
  /deep/.ant-col-24 {
    width: 40%;
  }

  /deep/.ant-form-item-control-wrapper {
    position: relative;
    top: -10px;
  }
}

/deep/.ant-space-item {
  display: block;
  width: 45%;
  flex: none;
}
</style>
